package app.kit;

import app.dtos.SmsDto;
import app.models.analyze.Smsrecord;
import app.models.sys.Ismg;
import com.google.common.base.Strings;
import goja.GojaConfig;
import goja.StringPool;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.client.fluent.Request;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URLEncoder;

/**
 * <p> 短信发送接口 </p>
 *
 * @author sogYF
 * @version 1.0
 * @since JDK 1.6
 */
public class SmsKit {

    private static final Logger logger = LoggerFactory.getLogger(SmsKit.class);

    /**
     * 短信签名信息
     */
    public static final String SMS_SIGN = "融理财富";

    private static final String REGISTER_TPL  = "验证码：%s。请在5分钟内完成验证。如非本人操作请致电%s";
    private static final String TRADE_TPL     = "交易信息：尊敬的用户恭喜您交易成功，交易额为：%s，获得积分为：%s，使用积分为：%s。如非本人操作请致电%s";
    private static final String TRADE_PWD_TPL = "尊敬的客户，[%s](找回交易密码验证码),30分钟内有效";
    private static final String TRANSFER_TPL  = "尊敬的客户，[%s](转让申请交易验证码),30分钟内有效";
    private static final String REDEMPTION_TPL  = "尊敬的客户，[%s](产品赎回验证码),30分钟内有效";
    private static final String TRANSFER_SUCCESS_TPL  = "交易信息：尊敬的用户恭喜您转让的产品%s交易成功。如非本人操作请致电%s";


    private static final String PARAM_URL = "?name=%s&pwd=%s&mobile=%s&content=%s&sign=&stime=&type=pt&extno=";

    private static Ismg imsg;

    private SmsKit() { }

    public static void init() {
        imsg = Ismg.dao.findByDefault();
    }

    /**
     * 注册验证码
     * @param phone 手机号码
     */
    public static void registered(String phone) {
        String randomCode = RandomStringUtils.randomNumeric(6);
        final String content = String.format(REGISTER_TPL, randomCode, imsg.getStr("tel"));
        final String response = send(content, phone);
        if (!Strings.isNullOrEmpty(response)) {
            // 发送记录短信记录的消息，异步处理
            final DateTime now = DateTime.now();
            SmsDto event = SmsDto.createByRegister(phone, content, DateTime.now(), now, response);
            Smsrecord.dao.record(event);
        }

        SmsCodeKit.registed(phone, randomCode);
    }

    /**
     * 交易密码验证
     * @param phone 手机号码
     */
    public static void tradeSuccess(String phone, String productName ) {

        String content = String.format(TRANSFER_SUCCESS_TPL, productName,imsg.getStr("tel"));

        final String respone = send(content, phone);
        if (!Strings.isNullOrEmpty(respone)) {
            // 发送记录短信记录的消息，异步处理
            final DateTime now = DateTime.now();
            SmsDto event = SmsDto.createByRegister(phone, content, DateTime.now(), now, respone);
            Smsrecord.dao.record(event);
        }

    }
    /**
     * 交易密码验证
     * @param phone 手机号码
     */
    public static void tradePwd(String phone) {
        String randomCode = RandomStringUtils.randomNumeric(6);

        String content = String.format(TRADE_PWD_TPL, randomCode);

        final String respone = send(content, phone);
        if (!Strings.isNullOrEmpty(respone)) {
            // 发送记录短信记录的消息，异步处理
            final DateTime now = DateTime.now();
            SmsDto event = SmsDto.createByRegister(phone, content, DateTime.now(), now, respone);
            Smsrecord.dao.record(event);
        }


        SmsCodeKit.tradepwd(phone, randomCode);
    }

    /**
     * 转让交易 密码 短信
     *
     * @param phone 手机号码
     */
    public static void transfer(String phone) {
        String randomCode = RandomStringUtils.randomNumeric(6);

        String content = String.format(TRANSFER_TPL, randomCode);

        final String respone = send(content, phone);
        if (!Strings.isNullOrEmpty(respone)) {
            // 发送记录短信记录的消息，异步处理
            final DateTime now = DateTime.now();
            SmsDto event = SmsDto.createByRegister(phone, content, DateTime.now(), now, respone);
            Smsrecord.dao.record(event);
        }

        SmsCodeKit.transfer(phone, randomCode);
    }

    /**
     *赎回产品 密码 短信
     *
     * @param phone 手机号码
     */
    public static void redemption(String phone) {
        String randomCode = RandomStringUtils.randomNumeric(6);

        String content = String.format(REDEMPTION_TPL, randomCode);

        final String respone = send(content, phone);
        if (!Strings.isNullOrEmpty(respone)) {
            // 发送记录短信记录的消息，异步处理
            final DateTime now = DateTime.now();
            SmsDto event = SmsDto.createByRegister(phone, content, DateTime.now(), now, respone);
            Smsrecord.dao.record(event);
        }

        SmsCodeKit.redemption(phone, randomCode);
    }

    /**
     * 交易成功
     * @param amount 交易金额
     * @param intergral 积分
     * @param phone 电话号码
     */
    public static void trade(Double amount, int intergral, String phone) {
        final String content = String.format(TRADE_TPL, amount, intergral, 0, imsg.getStr("tel"));
        final String response = send(content, phone);
        if (!Strings.isNullOrEmpty(response)) {
            // 发送记录短信记录的消息，异步处理
            final DateTime now = DateTime.now();
            SmsDto event = SmsDto.createByRegister(phone, content, DateTime.now(), now, response);
            Smsrecord.dao.record(event);
        }

    }

    /**
     * 发送短信代码
     *
     * @param content 短信内容
     * @param phone   短信号码
     * @return 服务器返回信息
     */
    public static String send(String content, String phone) {

        String content_sign = "【" + SMS_SIGN + "】" + content;
        if(!GojaConfig.getPropertyToBoolean("app.test", false)){
            try {

                String url_join = String.format(PARAM_URL, imsg.getStr("username"), imsg.getStr("password"),
                        phone, URLEncoder.encode(content_sign, StringPool.UTF_8));
                return Request.Post(imsg.getStr("url") + url_join)
                        .connectTimeout(8000)
                        .socketTimeout(8000)
                        .execute()
                        .returnContent().asString();
            } catch (IOException e) {
                logger.error("send sms message has error!", e);
            }
            return null;
        }


        return StringPool.ZERO;

    }
}
